/**
 * Copyright (C) 2013 Aurélien Chabot <aurelien@chabot.fr>
 * <p>
 * This file is part of DroidUPNP.
 * <p>
 * DroidUPNP is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * <p>
 * DroidUPNP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * <p>
 * You should have received a copy of the GNU General Public License
 * along with DroidUPNP.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.ibo.demo.upnp;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Toast;

import com.hezb.clingupnp.DlnaDeviceInfo;
import com.hezb.clingupnp.DlnaSearch;
import com.hezb.clingupnp.dmc.UpnpActionCallBack;
import com.hezb.clingupnp.dmc.UpnpControlSet;
import com.ibo.demo.upnp.adapter.DeviceListAdapter;

import org.fourthline.cling.android.AndroidUpnpService;
import org.fourthline.cling.controlpoint.ControlPoint;
import org.fourthline.cling.model.meta.Device;
import org.fourthline.cling.registry.DefaultRegistryListener;
import org.fourthline.cling.registry.Registry;
import org.fourthline.cling.registry.event.DeviceDiscovery;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


public class Main extends AppCompatActivity {
    private static final String TAG = "###  Main";
    private static final int REQUEST_READ_EXT_STORAGE = 12345;

//    private AndroidUpnpService mUpnpService;
//
//    ServiceConnection serviceConnection = new ServiceConnection() {
//        @Override
//        public void onServiceConnected(ComponentName name, IBinder service) {
//            mUpnpService = (AndroidUpnpService) service;
//            mUpnpService.getControlPoint().getRegistry().removeAllRemoteDevices();// 先清除掉之前的，再搜索
//            mUpnpService.getRegistry().addListener(mDefaultRegistryListener);
//            mUpnpService.getControlPoint().search();
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName name) {
//            mUpnpService = null;
//        }
//    };
//
//    private DefaultRegistryListener mDefaultRegistryListener = new DefaultRegistryListener() {
//
//        @Override
//        public void deviceAdded(Registry registry, Device device) {
//            System.out.println("######  deviceAdded: " + device.getDisplayString());
//        }
//
//        @Override
//        public void deviceRemoved(Registry registry, Device device) {
//            System.out.println("######  deviceRemoved: " + device.getDisplayString());
//        }
//    };
//
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//        if (Build.VERSION.SDK_INT >= 23) {
//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXT_STORAGE);
//            }
//        }
//
//
//        bindService(new Intent(this, MyUpNpService.class), serviceConnection, Context.BIND_AUTO_CREATE);
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//
//        if (mUpnpService != null) {
//            mUpnpService.getRegistry().removeListener(mDefaultRegistryListener);
//        }
//        unbindService(serviceConnection);
//        mUpnpService = null;
//    }


    private DlnaSearch mDlnaSearch;
    private List<Device> deviceList = new ArrayList<>();
    private DeviceListAdapter adapter;
    private EditText et;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXT_STORAGE);
            }
        }
        EventBus.getDefault().register(this);

        mDlnaSearch = new DlnaSearch(this);
        mDlnaSearch.startSearchDMC();

        et = (EditText) findViewById(R.id.et);
        et.setText("https://vodkgeyttp8.vod.126.net/cloudmusic/JCAwNSIwMSQgICJgNSQkMA==/mv/5381059/f86389f93480bd7d82fb4c3f350f059f.mp4?wsSecret=1901b361cebf19db05fb6744103d33bd&wsTime=1544603381");

        findViewById(R.id.play_pauseButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(), WebPlayAct.class));
            }
        });

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rc);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new DeviceListAdapter(deviceList);
        adapter.setDeviceListener(new DeviceListAdapter.DeviceClickListener() {
            @Override
            public void onDeviceSelected(Device device) {
                UpnpControlSet upnpControlSet = mDlnaSearch.createUpnpControlSet(device);
                upnpControlSet.setAVTransportURI(getAddr(), 0, "ok");
                upnpControlSet.setUPnPActionCallBack(new UpnpActionCallBack() {
                    @Override
                    public void onSuccess(int type) {
                        System.out.println("#### onSuccess  " + type);
                    }

                    @Override
                    public void onFailure(int type, String error) {
                        System.out.println("#### onFailure  " + type + "   " + error);
                    }

                    @Override
                    public void getVolumeReceived(int volume) {
                        System.out.println("#### getVolumeReceived  " + volume);
                    }

                    @Override
                    public void getTransportReceived(boolean isPlaying) {
                        System.out.println("#### getTransportReceived  " + isPlaying);
                    }

                    @Override
                    public void getPositionInfoReceived(int currentPosition, int duration) {
                        System.out.println("#### getPositionInfoReceived  " + currentPosition + "   " + duration);
                    }
                });
                System.out.println("####  onDeviceSelected : " + device.getDetails().getFriendlyName());
            }
        });
        recyclerView.setAdapter(adapter);

    }

    private String getAddr() {
        return et.getText().toString().trim();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mDlnaSearch.resumeSearch();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mDlnaSearch.pauseSearch();
    }

    @Override
    protected void onDestroy() {
        mDlnaSearch.unBindService();
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }


    //发现设备是回调
    public void onEventMainThread(DlnaDeviceInfo dlnaDeviceInfo) {
        Log.d(TAG, "onEventMainThread: " + dlnaDeviceInfo.getDevice().getDetails().getFriendlyName());

        if (dlnaDeviceInfo.isAdd()) {
            deviceList.add(dlnaDeviceInfo.getDevice());
        } else {
            String removeIdentifier = dlnaDeviceInfo.getDevice().getIdentity()
                    .getUdn().getIdentifierString();
            String identifier = null;
            for (int i = 0; i < deviceList.size(); i++) {
                identifier = deviceList.get(i).getIdentity().getUdn().getIdentifierString();
                if (identifier.equals(removeIdentifier)) {
                    deviceList.remove(i);
                    break;
                }
            }
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }


}
